// 引入express 框架
const express = require("express");
const cors =require("cors");
const db =require("./../libs/DBHelper");
const md5=require("md5");
const fs = require("fs");

// 创建保安大爷
const aipRouter = express.Router(/* 路径的严格相等的参数*/);

// cors  已经安全级别很低了，要么使用webpack proxy代理，就可以不用跨域
aipRouter.use("*",cors(), function(request,response,next){
    response.setHeader("Content-Type","application/json;charset=utf-8");
    // 设置跨域
    // response.setHeader("Access-Control-Allow-Origin","*");
    next();
});
// 给保安大爷 介绍活
// 注册
aipRouter.post("/reg",async function(request,response,next){

    //1. 得到前端的数据
    let users=request.body;
    // 2.得到数据库对象,进行插入
    let sql="INSERT INTO `userinfo` (`u_Name`,`u_Pwd`,`u_Phone`)VALUES(?,?,?);";
    let parmas=[
        users.uname,
        md5(users.upwd),
        users.uphone
    ];

    try {
        // 有可能出错的地方  又网络请求的地方，建议使用try...catch,数据库连接，ajax请求
    let res=await db.executeAsync(sql,parmas); 
       if(res&&res.affectedRows==1){
            response.json({msg:"注册成功","status":200});
       }else{
            response.json({msg:"注册失败","status":-200});
       }
    } catch (error) {
        // 有错误就执行 catch
        response.json({msg:"注册异常", info:error});
    }finally{
        // 不管有没有错都执行
    }
});

// 登陆
// 给保安大爷 介绍活
aipRouter.post("/login",async function(request,response,next){

    //1. 得到前端的数据
    let users=request.body;
    // 2.得到数据库对象,进行插入
    let sql="SELECT `u_Id`,`u_Name`,`u_Phone`,`u_Avatar` FROM `userinfo` WHERE u_Name=? AND u_Pwd=? AND u_status=1;";
    let parmas=[
        users.uname,
        md5(users.upwd)
    ];

    try {
        // 有可能出错的地方  又网络请求的地方，建议使用try...catch,数据库连接，ajax请求
    let res=await db.executeAsync(sql,parmas); 
       if(res && res.length>=1){
            response.json({msg:"登陆成功","status":200,data:res});
       }else{
            response.json({msg:"登陆失败","status":-200});
       }
    } catch (error) {
        // 有错误就执行 catch
        response.json({msg:"登陆异常", info:error});
    }finally{
        // 不管有没有错都执行
    }
});

aipRouter.post("/addCart",async function(request,response,next){
    let data=request.body;
    // id: "2"
    // imgbig: (3) ["images/xiangqing2-1-1.jpg", "images/xiangqing2-2-1.jpg", "images/xiangqing2-3-1.jpg"]
    // mainImg: "images/xiangqing2-1.jpg"
    // num: 1
    // price: "87.9"
    // title: "＄刀唛芥花籽油(5L)"
    // total: 87.9
    // u_id: 17
    
    let querySQL="SELECT*FROM cartlist WHERE u_Id=? AND p_id=? AND c_status=1 ;"
    let paramsQuery=[data.u_id,data.id];

    let queryList= await db.executeAsync(querySQL,paramsQuery);

    if(queryList.length == 1){
        let updateSql="UPDATE cartlist SET c_num=c_num+? , c_total=c_num*c_price WHERE u_Id=? AND p_id=? AND c_status=1;";
        let updatePrams=[data.num,data.u_id,data.id];
        
        try {
            let res=await db.executeAsync(updateSql,updatePrams);

            if(res&& res.affectedRows >=1){
                response.json({msg:"加入成功u",status:200});
            }else{
                response.json({msg:"加入失败u",status:-200});
            }
        } catch (error) {
            response.json({msg:"加入异常u",error});
        }

    }else{
        let insertSQL="INSERT INTO `cartlist` (`c_Name`,`c_price`,`c_num`,`c_total`,`c_img`,`u_Id`,`p_id`)VALUES (?,?,?,?,?,?,?);";

        let paramsInert=[data.title,data.price,data.num,data.total,data.mainImg,data.u_id,data.id];
    
        try {
            let res=await db.executeAsync(insertSQL,paramsInert);
            if(res&&affectedRows ==1){
                response.json({msg:"加入成功i",status:200});
            }else{
                response.json({msg:"加入失败i",status:-200});
            }
        } catch (error) {
            // response.json({msg:"加入异常i",error});
        }
    }
})

    // id: "2"
    // imgbig: (3) ["images/xiangqing2-1-1.jpg", "images/xiangqing2-2-1.jpg", "images/xiangqing2-3-1.jpg"]
    // mainImg: "images/xiangqing2-1.jpg"
    // num: 1
    // price: "87.9"
    // title: "＄刀唛芥花籽油(5L)"
    // total: 87.9
    // u_id: 17

// 加载购物车
aipRouter.get("/cart",async function(request,response,next){

    let uid = request.query.uid;

    let sql="SELECT *FROM cartlist WHERE c_status=1 AND u_Id=? ;";
    let params = [uid];

    try {
        let res=await db.executeAsync(sql,params);
        
        let result = res.length >= 1 ? {msg:"查询成功","status":200, data:res}:{msg:"查询失败","status":-200}
        response.json(result);           
        
    } catch (err) {
        
    }
});

// 修改数量
aipRouter.post("/updateCart",async function(request,response,next){
    let data=request.body;
    let sql="UPDATE cartlist SET c_num=? , c_total=c_num*c_price WHERE c_Id=? AND c_status=1;";
    let params = [data.c_num,data.c_Id];

    try {
        let res = await db.executeAsync(sql,params);
        console.log(data);
        console.log(res);

        if(res&&res.affectedRows >=1){
            response.json({msg:"修改成功",status:200});
        }else{
            response.json({msg:"修改失败",status:-200});
        }
    } catch (error) {
        response.json({msg:"修改异常",info: err});
    }
    
})

// 删除  软删除
aipRouter.post("/deleteCart",async function(request,response,next){
    let cid=request.body.c_Id;
    let sql="UPDATE cartlist SET c_status=0 WHERE c_Id=? AND c_status=1;";
    let params = [cid];

    try {
        let res = await db.executeAsync(sql,params);
        if(res && res.affectedRows==1){
            response.json({msg:"删除成功",status:200});
        }else{
            response.json({msg:"删除失败",status:-200});
        }
    } catch (err) {
        response.json({msg:"删除异常",info:err});
    }
})

aipRouter.get("/list",function(request,response,next){
    response.json(JSON.parse(fs.readFileSync("./data/data.json").toString()));
});

// 动态路由  :pid+params
aipRouter.get("/info/:pid",function(request,response,next){
    let pid=request.params.pid;
    let res=JSON.parse(fs.readFileSync("./data/data.json").toString()).filter(function(el){
        return el.id==pid
    });
    response.json(res);
});


module.exports = aipRouter;
